<template id="pay">
	<div class="pay">

		<!--头部-->
		<div class="about_header">

			<div class="about_title">
				<img src="../../assets/images/class/jiantou_03.png" @click.stop="back" />

				<p>充值台</p>
				<div class="about_select">
					<div class="about_ing"></div>
				</div>

			</div>
		</div>
		<!--头部结束-->

		<!--待支付金额-->
		<div class="pay_sum">
			<p>待支付金额</p>
			<div class="pay_amount">￥<span>{{price -yuan}}</span></div>
			<!-- <div class="pay_data">剩余支付时间：<span>{{sumDate}}</span></div> -->
		</div>
		<!--待支付金额结束-->

		<!--支付方式-->
		<div class="pay_mode">
			<p>支付方式</p>

			<div class="pay_pattern">

				<div id="weixinin" class="pay_weixin" @click.stop="weiXin">
					<div class="pay_left"><img src="../../assets/images/pay/pay_11.png" /><span>微信支付</span></div>
				</div>
        <div id="weixinon" class="pay_weixin" @click.stop="weiXinH5">
          <div class="pay_left"><img src="../../assets/images/pay/pay_11.png" /><span>微信支付</span></div>
        </div>
				<!-- <div class="pay_weixin" @click.stop="join">
					<div class="pay_left"><img src="../../assets/images/pay/pay_19.png" /><span>余额支付</span></div>
				</div> -->


			
			</div>

		</div>
		<!--支付方式结束-->
		<div class="phonenum-show" v-show='messagepacket'>
			<div class="getback-title">
				余额支付<span @click="getbackMoneyclock()"><b>X</b></span>
			</div>
			<div class="write-phonenum">
				<p style="font-size: 15px;">请输入短信验证码</p>
				<input maxlength="6" class="realInput" v-model="realInput" id="focusid">
				<ul class="write-input clearfix">
					<li @click="myFocus">{{disInputs[0].value}}</li>
					<li v-for="(disInput, index) in disInputs" v-if="index!=0">{{disInput.value}}</li>
				</ul>
			</div>
			<div style="width: 100%;text-align: center;padding-top:20px ;">
				<button style="border: none;background: #2d8f90;color: white;width: 80%;height: 40px;margin: 0 auto;" @click.stop="comfirmSubmit">确认提交</button>
			</div>

		</div>

		<!--微信支付248元-->
		<!-- <div class="pay_to" @click.stop="payLogin($event)">{{number}}{{price}}元</div> -->
		<!--微信支付248元结束-->

	</div>
</template>

<script>
	import { Toast } from 'mint-ui';
  import crypto from 'crypto';
	export default {
		data() {
			return {
				pay: '0',
				price: '',
				create_time: '',
				//number: "微信支付",
				code: '', //验证码
				phone: '',
				messagepacket: false,
				packets: [],
				disInputs: [{
					value: ''
				}, {
					value: ''
				}, {
					value: ''
				}, {
					value: ''
				}, {
					value: ''
				}, {
					value: ''
				}],
				realInput: '',
				inputArr: [],
				bookingid: this.$route.query.bookingid,
				couponid: this.$route.query.couponid,
				create_time: this.$route.query.create_time,
				payDate: '',
				tsMessage: '',
				// sumDate: '',
				num: '',
				time: '',
				mweb: '',
				yuan:this.$route.query.yuan
			}
		},
		mounted(){
		},
		methods:{
		},
		created() {
			var num=JSON.parse(window.localStorage.getItem('num'))
      var ua = window.navigator.userAgent.toLowerCase();
      //通过正则表达式匹配ua中是否含有MicroMessenger字符串
      setInterval(function(){
        if(ua.match(/MicroMessenger/i) == 'micromessenger'){
          console.log("微信内")
          $('#weixinon').css('display','none');
        }else{
          $('#weixinin').css('display','none');
        }
      },50);
			console.log(num.coupon)
			this.yuan=Number(num.coupon)
			this.price = this.$route.query.price
			this.create_time = this.$route.query.create_time
			let obj = {

			};
			let _this = this
			let qs = require('qs');
			this.$axios.post("/Scanning/user/getSystemTime", qs.stringify(obj), {
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded'
				}
			}).then(function(response) {
				_this.payDate = response.data.data

				_this.clearMyInterval = setInterval(() => {
					_this.payDate = _this.payDate + 1000;
					_this.sumDate = _this.formatDate(_this.countTime(_this.payDate));
					if(_this.payDate < 0) {
						clearInterval(_this.clearMyInterval)
					}
				}, 1000)

			}).catch(function(error) {
				console.log(error);
			});
			if(typeof WeixinJSBridge == "undefined") {
				if(document.addEventListener) {
					document.addEventListener('WeixinJSBridgeReady', onBridgeReady,
						false);
				} else if(document.attachEvent) {
					document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
					document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
				}
			} else {
				onBridgeReady();
			}
		},

		watch: {
			realInput(val) {
				this.inputArr = val
				for(let i = 0; i < this.disInputs.length; i++) {
					this.disInputs[i].value = this.inputArr[i];
				}
			}
		},
		filters: {
			formatDate(value) {
				let date = new Date(value);
				let m = date.getMinutes();
				m = m < 10 ? ('0' + m) : m;
				let s = date.getSeconds();
				s = s < 10 ? ('0' + s) : s;
				return m + ':' + s;
			},
			
		},
		beforeRouteLeave(to, from, next) {
			clearImmediate(this.clearMyInterval); // 路有变化清除计时器
			next();
		},
		methods: {
			formatDate(value) {
				let date = new Date(value);
				let m = date.getMinutes();
				m = m < 10 ? ('0' + m) : m;
				let s = date.getSeconds();
				s = s < 10 ? ('0' + s) : s;
				return m + ':' + s;
			},
			countTime(time) {

				let _this = this
				let ten = 600000;
				const startTime = parseInt(_this.create_time);
				const endTime = parseInt(time);
				const msec = endTime - startTime;
				const residue = ten - msec;
				_this.sumDate = residue;

				let min = parseInt(residue / 1000 / 60 % 60);
				let sec = parseInt(residue / 1000 % 60);
				_this.min = min > 9 ? min : '0' + min;
				_this.sec = sec > 9 ? sec : '0 ' + sec;
				return residue;
			},

			weiXin() {
				//let SESSION_ID = JSON.parse(window.sessionStorage.getItem('SESSION_ID'));
				var SESSION_ID=JSON.parse(window.localStorage.getItem('sessiond'))
				let open = window.localStorage.getItem("openid");
				let coupond = this.$route.query.couponid;
				if(coupond==null||coupond==""){
					coupond=0;
				}
				let obj = {
					userid: SESSION_ID.user.id,
					//cuserid: '',// 被充值的用户ids
					payOrRecharge: 2, // 支付还是充值 1 支付 2 充值
					price: this.$route.query.price - this.yuan, // 充值 / 支付价格
					bookingid: this.$route.query.bookingid, // 支付订单id
					title: 123456,
					couponid: coupond,
					openid: open,
					//cartid: '',// 如果是购物车支付 / 购物车订单id
				};
				let _this = this
				let qs = require('qs');
				var appid = "";
				var mch_id = "";
				var prepay_id = "";
				var orederid = "";
				var mweb_url = "";
				var nonceStr = "";
				var timeStamp = "";
				var finalsign = "";
				var packages = "";
				var booking = $('#booking').val();
				var signstr = "";
				var sign = "";
				this.$axios.post("/Scanning/pay/wxpay", qs.stringify(obj), {
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded'
					}
				}).then(function(response) {
					if(response.data.code == 0) {
						appid = response.data.paydata.appid;
						mch_id = response.data.paydata.mch_id;
						prepay_id = response.data.paydata.prepay_id;
						orederid = response.data.paydata.orederid;
						mweb_url = response.data.paydata.mweb_url;
						nonceStr = response.data.paydata.nonceStr;
						timeStamp = response.data.paydata.timeStamp;
						finalsign = response.data.paydata.finalsign;
						packages = response.data.paydata.packages;
						signstr = "appId=" + appid + "&nonceStr=" + nonceStr + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp + "&key=woniu888woniu888woniu888woniu888";
            var md5 = crypto.createHash("md5");
            md5.update(signstr);
            sign = md5.digest('hex');
						sign = sign.toUpperCase();
						console.log("加密加密前字符串为: " + signstr);
						console.log("加密加密后字符串为: " + sign);
					}
					WeixinJSBridge.invoke('getBrandWCPayRequest', {
						"appId": appid, //公众号名称，由商户传入     
						"timeStamp": timeStamp, //时间戳，自1970年以来的秒数     
						"nonceStr": nonceStr, //随机串     
						"package": "prepay_id=" + prepay_id,
						"signType": "MD5", //微信签名方式：     
						"paySign": sign //微信签名 
					}, function(res) {
						console.log(res);
						if(res.err_msg == "get_brand_wcpay_request:ok") {
							// 使用以上方式判断前端返回,微信团队郑重提示：
							//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
							console.log("支付成功！");
                            mui.alert("支付成功");
                            _this.$router.push({
                                path: '/main_money',
                                query: {
                                }
                            })

						}else{
							console.log("支付失败!");
              mui.alert("网络异常或支付失败,请重试~");
						}
					});
				}).catch(function(error) {
					console.log(error);
				});
			},
      weiXinH5() {
        //let SESSION_ID = JSON.parse(window.sessionStorage.getItem('SESSION_ID'));
        var SESSION_ID=JSON.parse(window.localStorage.getItem('sessiond'))
        let open = sessionStorage.getItem("openid");
        let coupond = this.$route.query.couponid;
        if(coupond==null||coupond==""){
          coupond=0;
        }
        let obj = {
          userid: SESSION_ID.user.id,
          //cuserid: '',// 被充值的用户ids
          payOrRecharge: 1, // 支付还是充值 1 支付 2 充值
          price: this.$route.query.price - this.yuan, // 充值 / 支付价格
          bookingid: this.$route.query.bookingid, // 支付订单id
          title: 123456,
          couponid: coupond,
          openid: open,
          //cartid: '',// 如果是购物车支付 / 购物车订单id
        };
        let _this = this
        let qs = require('qs');
        var appid = "";
        var mch_id = "";
        var prepay_id = "";
        var orederid = "";
        var mweb_url = "";
        var nonceStr = "";
        var timeStamp = "";
        var finalsign = "";
        var packages = "";
        var booking = $('#booking').val();
        var signstr = "";
        var sign = "";
        this.$axios.post("http://yogahome.shop/Scanning/pay/wxpayH5", qs.stringify(obj), {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        }).then(function(response) {
          if(response.data.code == 0) {
            appid = response.data.paydata.appid;
            mch_id = response.data.paydata.mch_id;
            prepay_id = response.data.paydata.prepay_id;
            orederid = response.data.paydata.orederid;
            mweb_url = response.data.paydata.mweb_url;
            nonceStr = response.data.paydata.nonceStr;
            timeStamp = response.data.paydata.timeStamp;
            finalsign = response.data.paydata.finalsign;
            packages = response.data.paydata.packages;
            // signstr = "appId=" + appid + "&nonceStr=" + nonceStr + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp + "&key=woniu888woniu888woniu888woniu888";
            // var md5 = crypto.createHash("md5");
            // md5.update(signstr);
            // sign = md5.digest('hex');
            // sign = sign.toUpperCase();
            // console.log("加密加密前字符串为: " + signstr);
            // console.log("加密加密后字符串为: " + sign);
            console.log(response.data);
            window.location.href = mweb_url+"&redirect_url=http%3a%2f%2fyogahome.top%2fygweb%2f%23%2fdoudle_air_complete";
          }

        }).catch(function(error) {
          console.log(error);
        });
      },
			comfirmSubmit() {
				//let SESSION_ID = JSON.parse(window.sessionStorage.getItem('SESSION_ID'));
				var SESSION_ID=JSON.parse(window.localStorage.getItem('sessiond'))
				let qs = require('qs');
				let obj = {
					code: this.inputArr,
				};
				let obj1 = {
					sessionid: SESSION_ID.sessionid,
					coachid: this.$route.query.coachid,
					userid: SESSION_ID.user.id,
					cashPrice: this.$route.query.price,
					bookingid: this.$route.query.bookingid,
					couponid: this.$route.query.couponid
				};
				let that = this;
				this.$axios.post("/Scanning/user/checkVcodeTB", qs.stringify(obj), {
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded'
					}
				}).then(function(response) {
					console.log(response.data);
					if(response.data.code == '1') {
						that.$axios.post("http://yogahome.shop/yujia/user/userBalancePayment", qs.stringify(obj1), {
							headers: {
								'Content-Type': 'application/x-www-form-urlencoded'
							}
						}).then(function(res) {
							if(res.data.code == '1') {
								Toast({
									message: res.data.message,
									position: 'top',
									duration: 5000
								});
							} else if(response.data.code == "-3") {
								Toast({
									message: res.data.message,
									position: 'top',
									duration: 5000
								});
							} else {
								Toast({
									message: res.data.message,
									position: 'top',
									duration: 5000
								});
							}
						}).catch(function(error) {
							console.log(error);
						});
					}
				}).catch(function(error) {
					console.log(error);
				});
			},
			getbackMoneyclock() {
				this.messagepacket = false
			},

			Pay: function(index) {
				this.pay = index

			},
			payLogin(e) {

			},

			back() {
				this.$router.push({
					path: '/main_money',
					query: {}
				})
			},
			//weixin() {
				
	//	this.number = "微信支付"
			//},
			myFocus() {
				var idObj = document.getElementById('focusid');
				idObj.focus();

			},
			// join() {
			// 	this.messagepacket = true;
			// 	//let SESSION_ID = JSON.parse(window.sessionStorage.getItem('SESSION_ID'));
			// 	var SESSION_ID=JSON.parse(window.localStorage.getItem('sessiond'))
			// 	let phone = this.phone;
			// 	let code = this.code;
			// 	let obj = {
			// 		phone: SESSION_ID.user.phone,
			// 	};

			// 	let _this = this
			// 	let qs = require('qs');
			// 	this.$axios.post("/Scanning/user/captchaNew", qs.stringify(obj), {
			// 		headers: {
			// 			'Content-Type': 'application/x-www-form-urlencoded'
			// 		}
			// 	}).then(function(response) {
			// 		console.log(response.data)
			// 		if(response.data.code == 1) {
			// 			mui.alert("短信发送成功")

			// 		} else if(response.data.code == -1) {
			// 			mui.alert("短信发送异常")
			// 		}

			// 	}).catch(function(error) {
			// 		console.log(error);
			// 	});
			// },
			//doc() {

			//	this.number = "余额支付"
			//},
			//zfuba() {
			//	this.number = "支付宝支付"
			//}
		},

	}
</script>

<style scoped>
	@import "../../assets/css/pay.css";
	.phonenum-show {
		padding: 10px;
		background: #f1f1f1;
		width: 80%;
		height: 200px;
		position: absolute;
		z-index: 10;
		top: 50%;
		left: 50%;
		margin-top: -50%;
		margin-left: -40%
	}
	
	.getback-title {
		padding-bottom: 10px;
		border-bottom: 1px solid #dddddd;
		position: relative;
		font-size: 14px;
		margin-bottom: 10px;
	}
	
	.getback-title span {
		position: absolute;
		right: 0;
		top: 3px;
		width: 15px;
		height: 15px;
		display: inline-block;
	}
	
	.write-phonenum p {
		text-align: center;
		font-size: 12px;
	}
	
	.write-phonenum p span {
		color: #3b90d1;
	}
	
	.write-input {
		border: 1px solid #888888;
		width: 195px;
		margin: 10px auto;
		overflow: hidden;
		background: #f1f1f1;
	}
	
	.write-input li {
		float: left;
		width: 30px;
		height: 30px;
		text-align: center;
		line-height: 30px;
		border-right: 1px solid #BFBFBF;
		background: white;
		margin-right: 2px;
	}
	
	.write-input li:last-child {
		border-right: none;
		margin-right: 0;
	}
	
	.write-phonenum .mint-button--default {
		background: #3b90d1;
		color: #fff;
		font-family: "微软雅黑";
		font-size: 14px;
		width: 80%;
		margin: 10px auto;
	}
	
	.realInput {
		-webkit-appearance: none;
		-moz-appearance: none;
		-ms-appearance: none;
		resize: none;
		outline: none;
		border: 0;
		z-index: 1;
		position: absolute;
		width: 186px;
		height: 32px;
		line-height: 32px;
		background: none;
		display: block;
		left: 50%;
		margin-left: -93px;
		top: 76px;
		opacity: 0;
		font-size: 0px;
		caret-color: #fff;
		color: #000;
		text-indent: -5em;
	}
</style>
